<template>
  <div class="message">
    <h2>发送消息给全体会员</h2>
    <el-form :model="form" label-width="150px" ref="form">
      <el-form-item label="要发送的消息" prop="message" :rules="[{ required: true, message: '内容不能为空'}]">
        <el-input
          type="textarea"
          maxlength="500"
          show-word-limit
          :autosize="{minRows: 3}"
          v-model="form.message"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="sendMessageForAllUser('form')">发送</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions, mapState } from "Vuex";
export default {
  name: "admin-message",
  data() {
    return {
      form: {
        message: ""
      }
    };
  },
  computed: {
    ...mapState("user", ["userInfoData", "userName"])
  },
  methods: {
    sendMessageForAllUser(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.getAllUserData({ limit: 500, skip: 0 })
            .then(res => {
              if (res.data.ok === 1) {
                let userData = res.data.data;
                for (let i = 0; i < userData.length; i++) {
                  if (userData[i].userName !== this.userName) {
                    this.sendMessageToUser({
                      text: this.form.message,
                      sendUserName: this.userName || this.userInfoData.userName,
                      userName: userData[i].userName,
                      sendCoverUrl: this.userInfoData.coverUrl || ""
                    })
                      .then(res => {
                        console.log(res.data.data);
                      })
                      .catch(err => {
                        console.log("错误信息：" + err);
                      });
                  }
                }
                alert("消息发送成功！");
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    ...mapActions("user", ["sendMessageToUser", "getAllUserData"])
  }
};
</script>

<style lang="sass" scoped>
@import '@/assets/default.sass'
.message
  width: 100%
  min-height: 700px
  padding: 20px
  >h2
    line-height: 60px
    color: #333
    border-bottom: 1px solid #eee
  .el-form
    margin-top: 20px
    padding-right: 100px
</style>